<?php

class ArticleScript extends ScriptBase
{
	private $mongo = null;
	private $mysql = null;
	private $search = null;
	private $replace = null;
	private $readCollection = null;
	private $articleCollection = null;
	private $weixinCollection = null;

	public function __construct()
	{
		$this->search = [
			"'<script[^>]*?>.*?</script>'si", // 去掉 javascript 
			"'<style[^>]*?>.*?</style>'si", // 去掉 css
			"'//<!--[/!]*?[^<>]*?>'si", // 去掉 注释标记
			"'<!--[/!]*?[^<>]*?>'si", // 去掉 注释标记
		];
		$this->replace = [
			"", 
			"",
			"",
			""
		];
		$this->mongo = new MongoClient("mongodb://newbee:9^4%NbAdwS@115.28.18.40:27017");
		$this->mysql = n_api('mysql')->cname('weixin');
		$this->readCollection = $this->mongo->selectDB('weixin')->selectCollection('read');
		$this->articleCollection = $this->mongo->selectDB('weixin')->selectCollection('article');
		$this->weixinCollection = $this->mongo->selectDB('weixin')->selectCollection('mpListFina');
	}

	private function get_weixin_category()
	{
		$weixinCategoryMongo = $this->weixinCollection->find(['sogouid' => ['$ne' => null], 'isdel' => ['$ne' => 'Y']], ['_id'=>0, 'category'=>1]);
		$weixinCategory = iterator_to_array($weixinCategoryMongo);
		$categories = [];
		foreach ($weixinCategory as $value) {
			$categories[] = $value['category'];
		}
		return array_unique($categories);
	}

	private function hot_article_handle($result, $category, $stime, $table)
	{
		foreach ($result as $value) {
			$article_mongoid = $value['articleId'];
			$checkExists = $this->mysql->fetchFirst("select id from article_details where article_mongoid = '$article_mongoid'");
			if (count($checkExists) > 0) {
				echo "already\n";
				continue;
				$mysql_article_id = $checkExists['id'];
				$update = [
					'read_num' => $value['readNum'],
					'like_num' => $value['likeNum'],
					'read_like' => $value['readLike'],
					'utime' => time()
				];
				$where = "article_id = '$mysql_article_id'";
				$this->mysql->update($table, $update, $where);
				echo $article_mongoid . " updated successfully\n";
			} else {
				$rs = $this->articleCollection->findOne(['_id' => new MongoId($article_mongoid)], ['content' => 0]);
				if ($rs['ptime'] == 0){
					echo $article_mongoid . " deleted\n";
					continue;
				}
				if ($rs == NULL) {
					// var
				}
				$wxid = $rs['wxid'];
				$time = time();

				try {
					$this->mysql->begin();
					$detailData = [
						'article_mongoid' => $article_mongoid,
						'title' => $rs['title'],
						//'digest' => $rs['digest'],
						'digest' => $rs['digest'],
						'url' => $rs['contentUrl'],
						'cover' => $rs['cover'],
						'article_ptime' => $rs['ptime'],
						'source_url' => $rs['sourceUrl'],
						'isTop' => $rs['isTop'] == 1 ? 'Y' : 'N',
						'ctime' => $time
					];
					$mysql_article_id = $this->mysql->insert('article_details', $detailData);

					$data = [
						'article_id' => $mysql_article_id,
						'wxid' => $wxid,
						'read_num' => $value['readNum'],
						'like_num' => $value['likeNum'],
						'read_like' => $value['readLike'],
						'daytime' => $stime,
						'ctime' => $time,
						'utime' => $time
					];
					$this->mysql->insert($table, $data);
					$this->mysql->commit();
				} catch (Exception $e) {
					var_dump($e->getMessage());
				}

				echo $article_mongoid . " added successfully\n";
			}
		}
	}

	public function hot_article_by_category_day()
	{
		set_time_limit(0);
		ini_set('memory_limit', '3072M');
		$weixin = n_api('weixin');
		
		$stime = strtotime(date('Y-m-d', strtotime('-1 day')));
		// var_dump(date('Y-m-d', $stime));exit;
		// $stime = 1452787200;
		$etime = $stime + 24 * 3600;

		$categories = $weixin->getCategories();
		foreach ($categories as $id => $category) {
			$rs = $weixin->getWxidsByCategoryId($id);
			$wxids = [];
			foreach ($rs as $value)
				$wxids[] = $value['wxid'];

			$rs = $this->readCollection->aggregate([
				['$match' => ['ptime' => ['$gte' => $stime, '$lt' => $etime], 'wxid' => ['$in' => $wxids]]],
				['$project' => ['_id' => 0, 'wxid' => 1, 'articleId' => 1, 'readNum' => 1, 'likeNum' => 1, 'readLike' => ['$add' => ['$readNum', ['$multiply' => ['$likeNum', 5]]]]]],
				['$sort' => ['readLike' => -1]]
			]);	

			if ($rs['ok']) {
				$this->hot_article_handle($rs['result'], $category, $stime, 'article_day');
			}
		}
		echo "one round finished\n";
	}

	public function hot_article_by_category_week()
	{
		$table = 'article_week';
		$stime = strtotime('-2 sunday');
		$etime = strtotime('-1 sunday');
		// $stime = 1443888000;
		// $etime = 1444406400;
		$weixin = n_api('weixin');

		$categories = $weixin->getGroupNames();
		foreach ($categories as $category) {
			$query = "select * from article_day where daytime >= $stime and daytime < $etime and category = '$category' order by read_like desc limit 100";
			$rs = $this->mysql->select($query);
			foreach ($rs as $value) {
				echo $value['wxname'] . "  ";
				$checkExists = $this->mysql->fetchFirst("select * from $table where article_id = {$value['article_id']}");
				if (count($checkExists) > 0) {
					$update['read_num'] = $value['read_num'];
					$update['like_num'] = $value['like_num'];
					$update['read_like'] = $value['read_like'];
					$update['utime'] = time();
					$where = "article_id = {$value['article_id']}";

					$this->mysql->update($table, $update, $where);
					echo $value['article_id'] . " updated successfully\n";
				} else {
					unset($value['daytime']);
					unset($value['id']);
					$data = $value;
					$time = time();
					$data['weektime'] = $stime;
					$data['ctime'] = $time;
					$data['utime'] = $time;
					$this->mysql->insert($table, $data);
					echo $value['article_id'] . " added successfully\n";
				}
			}
		} // end foreach
	}

	public function fuck()
	{
		$stime = 1452787200;
		$etime = $stime + 24 * 3600;
		$query = ['ptime' => ['$gte' => $stime, '$lt' => $etime]];
		$cursor = $this->articleCollection->findOne(["_id"=> new MongoId('5698e0707085644ca44f856f')]);
		
		$a = $cursor['digest'];
		$b = json_encode($a);
		$c = preg_replace("#(\\\ue[0-9a-f]{3})#ie","",$b);
		$d = json_decode($c);
		var_dump($d);
	}
}
